<template>
  <div>
    <h2>任务列表</h2>
    <div>
      <el-select v-model="filter" @change="filterTasks">
        <el-option label="所有任务" value="all" />
        <el-option label="已完成" value="completed" />
        <el-option label="未完成" value="incomplete" />
      </el-select>
    </div>
    <ul>
      <li v-for="(task, index) in filteredTasks" :key="index">
        <el-checkbox v-model="task.completed" @change="updateTaskStatus(task)">
          {{ task.name }}
        </el-checkbox>
        <el-button type="danger" @click="removeTask(index)"><el-icon><Delete /></el-icon> 删除 </el-button>
        <el-button @click="speakTask(index)"><el-icon><VideoPlay /></el-icon>播放</el-button>
        <el-button type="primary" @click="analysisTask(index)"><el-icon><ChatDotRound /></el-icon>AI分析任务</el-button>
      </li>
    </ul>
    <div v-if="renderedMarkdown">
      <h3>分析结果:</h3>
      <div v-html="renderedMarkdown" />
    </div>
  </div>
</template>

<script>
import { computed, onMounted, onBeforeMount, ref } from 'vue'
import { useStore } from 'vuex'
import { marked } from 'marked'

export default {
  setup() {
    const store = useStore()
    const filter = ref('all')
    const filteredTasks = ref([])
    const speech = ref({
      allVoices: [],
      synth: window.speechSynthesis
    })
    const renderedMarkdown = ref('')

    onBeforeMount(() => {
      speech.value.allVoices = speech.value.synth.getVoices()
      console.log('this.speech==', speech.value)
    })

    onMounted(() => {
      filteredTasks.value = allTasks.value
    })

    const allTasks = computed(() => store.getters.allTasks)

    const filterTasks = () => {
      if (filter.value === 'completed') {
        filteredTasks.value = allTasks.value.filter(task => task.completed)
      } else if (filter.value === 'incomplete') {
        filteredTasks.value = allTasks.value.filter(task => !task.completed)
      } else {
        filteredTasks.value = allTasks.value
      }
    }

    const removeTask = async index => {
      try {
        await store.dispatch('removeTask', index)
        console.log('任务删除成功！')
      } catch (error) {
        console.error('任务删除失败：', error)
      }
    }

    const updateTaskStatus = task => {
      // 这里可以添加逻辑来更新任务状态
    }

    const speakTask = index => {
      if (typeof SpeechSynthesisUtterance !== 'undefined') {
        if (speech.value.allVoices.length > 0) {
          const voiceUtt = new SpeechSynthesisUtterance(allTasks.value[index].name)
          voiceUtt.voice = speech.value.allVoices.filter(
            item => item.lang === 'zh-CN' && item.name.includes('(Natural)')
          )[0]
          speech.value.synth.speak(voiceUtt)
        } else {
          console.log('speech:', speech.value)
        }
      }
    }

    const analysisTask = async index => {
      try {
        const taskName = allTasks.value[index].name
        const qianfanClientId = import.meta.env.VITE_APP_QIANFAN_CLIENT_ID
        const qianfanClientSecret = import.meta.env.VITE_APP_QIANFAN_CLIENT_SECRET

        // 清空之前的结果
        renderedMarkdown.value = ''

        // 获取 Access Token
        const tokenResponse = await fetch(
          `/api/oauth/2.0/token?grant_type=client_credentials&client_id=${qianfanClientId}&client_secret=${qianfanClientSecret}`
        )
        const tokenData = await tokenResponse.json()
        const accessToken = tokenData.access_token

        if (accessToken) {
          // 发送流式请求
          const response = await fetch(
            `/api/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=${accessToken}`,
            {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                model: 'ERNIE-Speed-8K',
                messages: [
                  {
                    role: 'user',
                    content: taskName
                  }
                ],
                response_format: 'text',
                temperature: 0.8,
                system: '请分析以上任务该如何完成，给出方案',
                stream: true // 设置为 true 以启用流式响应
              })
            }
          )

          const reader = response.body.getReader()
          const decoder = new TextDecoder('utf-8')
          let resultData = ''
          while (true) {
            const { done, value } = await reader.read()
            if (done) break
            // 解码并处理每一段数据
            let message = decoder.decode(value, { stream: true })
            try {
              if (message.startsWith('data: ')) {
                message = message.slice(6) // 去掉前缀
              }
              const json = JSON.parse(message)
              // 提取需要的字段并转换为 Markdown
              if (json.result) {
                resultData += json.result
                // 将 Markdown 转换为 HTML
                renderedMarkdown.value = marked(resultData)
              }
            } catch (error) {
              console.error('JSON 解析错误:', error)
            }
          }
          console.log(resultData)
        } else {
          console.error('Access Token 获取失败')
        }
      } catch (error) {
        console.error('获取 Access Token 或调用文心一言 API 发生错误:', error)
      }
    }

    return {
      filter,
      filteredTasks,
      allTasks,
      filterTasks,
      updateTaskStatus,
      speakTask,
      analysisTask,
      removeTask,
      speech,
      renderedMarkdown
    }
  }
}
</script>

<style scoped>
/* 你可以在这里添加样式 */
</style>
